package com.ctrlspace.core.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.ctrlspace.model.User;
import com.ctrlspace.util.db.Database;

public class SessionDao {
	private static final String LOGIN_USER = "SELECT * from users WHERE username = ? AND password = ? LIMIT 1";

	public User loginUser(String username, String password) {
		Connection conn = Database.getInstance().getConnection();
		User result = null;

		try {
			PreparedStatement st = conn.prepareStatement(LOGIN_USER);
			st.setString(1, username);
			st.setString(2, password);

			ResultSet rs = st.executeQuery();

			// Username and password matches
			if (rs.next()) {
				result = new User();
				result.setId(rs.getInt("userId"));
				result.setUsername(rs.getString("username"));
				result.setEmail(rs.getString("email"));
				result.setFirstName(rs.getString("firstName"));
				result.setLastName(rs.getString("lastName"));
				result.setLastLogin(rs.getDate("lastLogin"));
				result.setLastIp(rs.getInt("lastIp"));

				return result;
			}
		} catch (SQLException e) {
			// Add custom exception
			e.printStackTrace();
		}

		return result;
	}
}
